//
//  ZYXSaleTicketViewController.m
//  MultiThreading
//  NSThread模拟线程安全问题 模拟3个子线程同时卖票
//

#import "ZYXSaleTicketViewController.h"

@interface ZYXSaleTicketViewController ()

/** 剩余票数 */
@property (nonatomic, assign) int       leftTicketsCount;
@property (nonatomic, strong) NSThread  *thread0;
@property (nonatomic, strong) NSThread  *thread1;
@property (nonatomic, strong) NSThread  *thread2;

@end

@implementation ZYXSaleTicketViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 默认有100张
    self.leftTicketsCount = 210;
    
    // 开启多条线程同时卖票
    self.thread0 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread0.name = @"售票员 A";
        self.thread0.threadPriority = 0.0;
    
    self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread1.name = @"售票员 B";
        self.thread1.threadPriority = 1.0;
    
    self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread2.name = @"售票员 C";
        self.thread2.threadPriority = 0.0;
}

/**
 * 卖票
 */
//- (void)saleTicket
//{
//    while (1) {
//
//            // 1.先检查票数
//            int count = self.leftTicketsCount;
//            if (count > 0) {
//                // 暂停
//                                [NSThread sleepForTimeInterval:0.02];
//                
//                // 2.票数 - 1
//                self.leftTicketsCount = count - 1;
//                
//                NSThread *current = [NSThread currentThread];
//                NSLog(@"%@ 卖了一张票, 剩余%d张票", current.name, self.leftTicketsCount);
//            } else {
//                // 退出线程
//                [NSThread exit];
//            }
//
//    }
//}

- (void)saleTicket
{
    while (1) {
        @synchronized(self) { // 加锁(只能用一把锁)
            int count = self.leftTicketsCount;
            if (count > 0) {
                
                [NSThread sleepForTimeInterval:0.02];
                
                self.leftTicketsCount = count - 1;
                
                NSThread *current = [NSThread currentThread];
                NSLog(@"%@ 卖了一张票, 剩余%d张票", current.name, self.leftTicketsCount);
            } else {
                [NSThread exit];
            }
        } // 解锁
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.thread0 start];
    [self.thread1 start];
    [self.thread2 start];
}


@end
